<?php
	
	$allowed_ext = array (
		  'pdf' => 'application/pdf',
		  'doc' => 'application/msword',
		  'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		  'ppt' => 'application/vnd.ms-powerpoint',
		  'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation ',
		  'prc' =>  'application/vnd.palm',
		  'chm' => 'application/x-chm',
		  'txt' => 'text/plain',
	);

	set_time_limit(0);

	if (!isset($_GET['f']) || empty($_GET['f'])) {
		header('Content-type: text/html; charset=utf-8');
	  die("Tên file không tồn tại");
	}
		$fname = $_GET['f'];
		$file_path = '../resources/files/'."$fname";

	if (!is_file($file_path)) {
		header('Content-type: text/html; charset=utf-8');
	  die("File không hợp lệ"); 
	}

	// file size in bytes
	$fsize = filesize($file_path); 

	// file extension
	$fext = strtolower(substr(strrchr($fname,"."),1));


	// get mime type
	if ($allowed_ext[$fext] == '') {
	  $mtype = '';
	  if ($mtype == '') {
	    $mtype = "application/force-download";
	  }
	}
	else {
	  $mtype = $allowed_ext[$fext];
	}

	// set headers
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: public");
	header("Content-Description: File Transfer");
	header("Content-Type: $mtype");
	header("Content-Disposition: attachment; filename=\"$fname\"");
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: " . $fsize);

	// download
	$file = @fopen($file_path,"rb");
	if ($file) {
	  while(!feof($file)) {
	    print(fread($file, 1024*8));
	    flush();
	    if (connection_status()!=0) {
	      @fclose($file);
	      die();
	    }
	  }
	  @fclose($file);
	}

	// luu vao csdl
	include '../common/db.inc';
	
	$conn = new mysqli($host, $username, $password, $dbname);	
	$conn->query("set names 'utf8'");
	
	$userId = $conn->real_escape_string($_GET['u']);
	$ebookId = $conn->real_escape_string($_GET['e']);
	
	$query = "call sp_AddFileTransfer('$userId', '$ebookId', '2')";
	@$conn->query($query);
	$conn->close();

	$conn = new mysqli($host, $username, $password, $dbname);	
	$conn->query("set names 'utf8'");
	$query = "call sp_GetUserById('$userId')";
	if($result = @$conn->query($query))
	{
		$row = mysqli_fetch_row($result);
		session_start();
		$_SESSION['user_mana'] = $row[5];
	}
	$conn->close();
?>